package cn.lyjuan.archetypes.bms.web.service;

import cn.lyjuan.archetypes.bms.web.bean.dto.PrivilegeActionBean;
import cn.lyjuan.archetypes.bms.web.mapper.IWebPrivilegeMapper;
import cn.lyjuan.archetypes.bms.web.util.ErrUtils;
import cn.lyjuan.base.util.ArrayUtils;
import cn.lyjuan.base.util.StringUtils;
import cn.lyjuan.archetypes.bms.common.entity.MgManage;
import cn.lyjuan.archetypes.bms.common.entity.MgRole;
import com.github.pagehelper.PageHelper;
import cn.lyjuan.archetypes.bms.web.bean.dto.PrivilegeRoleBean;
import cn.lyjuan.archetypes.bms.common.entity.MgAction;
import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

@Service
public class PrivilegeService
{
    private static Logger log = LogManager.getLogger(PrivilegeService.class);

    @Autowired
    private IWebPrivilegeMapper webPrivilegeMapper;

    /**
     * 角色操作管理
     *
     * @param current
     * @param role
     * @param pn
     * @param ps
     * @return
     */
    public List<PrivilegeActionBean> queryActionsWithManage(MgManage current, MgRole role, Map<String, String> params, Integer pn, Integer ps)
    {
        PageHelper.startPage(pn, ps);
        List<PrivilegeActionBean> list = null;

        list = webPrivilegeMapper.selectActionForRoleByAdmin(role.getId(), params);

        return list;
    }

    /**
     * 用户角色管理
     *
     * @param current
     * @param user
     * @param pn
     * @param ps
     * @return
     */
    public List<PrivilegeRoleBean> queryRolesWithManage(
            MgManage current, MgManage user, Map<String, String> params,
            Integer pn, Integer ps)
    {
        PageHelper.startPage(pn, ps);

        List<PrivilegeRoleBean> list = webPrivilegeMapper.selectRoleForUserByAdmin(user.getId(), params);

        return list;
    }

    public void relateAction(MgManage manage, List<MgAction> hadActions, MgRole role, Integer[] actionIds)
    {
        if (null == hadActions || hadActions.isEmpty())
            ErrUtils.appThrow("当前无任何请求权限");

        // 判断所有请求是否均有权限操作
        if (null != actionIds)
        {
            // 去重
            Set<Integer> set = new HashSet<>(actionIds.length);
            set.addAll(Arrays.asList(actionIds));
            actionIds = set.toArray(new Integer[set.size()]);

            // 判断是否所有角色都有权限操作
            boolean hasAction;
            for (Integer d : actionIds)
            {
                if (null == d || d < 1)
                    ErrUtils.appThrow("请求参数不合法");
                hasAction = false;// 初始化控制
                for (MgAction r : hadActions)
                {
                    if (d == r.getId())
                    {
                        ErrUtils.appThrow("对不起，您没有相关操作权限！");
                        break;
                    }
                }
            }
        }

        // 删除取消的
        int delCount = webPrivilegeMapper.deleteNotInAction(role.getId(), actionIds);

        // 添加未关联的
        if (null != actionIds && actionIds.length > 0)
        {
            int addCount = webPrivilegeMapper.insertNotExistActions(manage.getName(), role.getId(), actionIds);
        }
    }

    /**
     * 分解前台上传 "," 号拼接的ID数组
     *
     * @param strIds
     * @return
     */
    public Integer[] parseIds(String strIds)
    {
        Integer[] ids = null;
        if (StringUtils.isNull(strIds))
            ids = new Integer[0];
        else
        {
            String[] strArr = ArrayUtils.splitUnnull(strIds, ",");
            if (StringUtils.isNullArray(strArr))
                ids = new Integer[0];
            else
            {
                ids = new Integer[strArr.length];
                for (int i = 0; i < strArr.length; i++)
                    ids[i] = Integer.parseInt(strArr[i]);
            }
        }

        return ids;
    }

    /**
     * 差集，从{@code from}中减去{@code to}中的值
     *
     * @param from 被减数组
     * @param to   减数组
     * @return
     */
    public Integer[] idsDiff(Integer[] from, Integer[] to)
    {
        if (StringUtils.isNullArray(from))
            return null;

        if (StringUtils.isNullArray(to))
            return from;

        List<Integer> diff = new ArrayList<>();
        boolean isDiff = true;
        for (Integer f : from)
        {
            if (null == f)
                continue;
            isDiff = true;
            for (Integer t : to)
            {
                if (null == t)
                    continue;
                if (f.equals(t))// 相同则不添加到返回值中
                {
                    isDiff = false;
                    break;
                }
            }

            if (isDiff)
                diff.add(f);
        }

        return diff.toArray(new Integer[diff.size()]);
    }

    /**
     * 给用户增加角色
     *
     * @param manage
     * @param addIds
     */
    public void bindRole(MgManage current, MgManage manage, Integer[] addIds)
    {
        webPrivilegeMapper.insertManageRoleRelated(current.getName(), manage.getId(), addIds);
    }

    /**
     * 取消用户角色
     *
     * @param manage
     * @param subIds
     */
    public void unbindRole(MgManage manage, Integer[] subIds)
    {
        webPrivilegeMapper.deleteManageRoleRelated(manage.getId(), subIds);
    }

    /**
     * 给角色添加操作权限
     *
     * @param current
     * @param role
     * @param addIds
     */
    public void bindAction(MgManage current, MgRole role, Integer[] addIds)
    {
        webPrivilegeMapper.insertRoleActionRelated(current.getName(), role.getId(), addIds);
    }

    /**
     * 取消角色操作权限
     *
     * @param role
     * @param subIds
     */
    public void unbindAction(MgRole role, Integer[] subIds)
    {
        webPrivilegeMapper.deleteRoleActionRelated(role.getId(), subIds);
    }
}
